package com.LocalMarket.LocalMarketClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.LocalMarket.LocalMarketClient.Utils.ConfigurationController;
import com.LocalMarket.LocalMarketClient.Utils.ConnectionHandler;

public class LocalMarketAndroidClientActivity extends Activity {
    ConnectionHandler sessionConnection;
    
    TextView serverAddressForm;
    TextView serverPortForm;
    ProgressDialog updateDialog;
	
    ConfigurationController sessionConfiguration;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.serverAddressForm = (TextView) findViewById(R.id.serverAddressForm);
        this.serverPortForm = (TextView) findViewById(R.id.serverPortForm);
        
        this.sessionConfiguration = new ConfigurationController(this);
        this.serverAddressForm.setText(this.sessionConfiguration.GetServerAddress().toCharArray(),0,this.sessionConfiguration.GetServerAddress().toCharArray().length);
        this.serverPortForm.setText(this.sessionConfiguration.GetServerPort().toCharArray(),0,this.sessionConfiguration.GetServerPort().toCharArray().length);

    }
    
    public void ConnectToTheServer(View view){
    	this.updateDialog = ProgressDialog.show(this, this.sessionConfiguration.GetServerAddress()+":"+this.sessionConfiguration.GetServerPort(), "Updating server information");
    	
    	this.sessionConnection = new ConnectionHandler(this.sessionConfiguration.GetServerAddress(), Integer.parseInt(this.sessionConfiguration.GetServerPort()));
    	this.sessionConnection.SendMessage("CMD:srvInfo");
    	
    	if (this.sessionConfiguration.SetDefaultServer(this.serverAddressForm.getText().toString(), this.serverPortForm.getText().toString()))
        	Toast.makeText(this, "Settings Saved!", Toast.LENGTH_LONG).show();
    	else
        	Toast.makeText(this, "Settings NOT Saved!", Toast.LENGTH_LONG).show();
    
    	this.updateDialog.dismiss();
    }
    
    public void SendClose(View view){
    	String message="Message not sent!";
    	if (this.sessionConnection!=null){
    		if (this.sessionConnection.SendMessage("CMD:close"))
    			message="Message sent!";
    	}
    	else 
    		message = "You must first set a connection with the server";
    	Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
    

    
}
